<template>
  <el-container style="height:100%">
    <el-row :gutter="10" class="project-container">
      <el-col :span="6">
        <div v-show="true" class="tree-container">
          <tree-x :data="projectTreeData" @nodeClick="nodeClick"></tree-x>
        </div>
      </el-col>
      <el-col :span="18">
        <div class="data-container">
          <div v-show="showindex" class="data-list">
            <table-x
              @dataDownload="downloadFile"
              @dataOutput="outputData"
              @dataEdit="editData"
              @dataDelete="deleteData"
              @dataAdd="addNewProject"
              :tableData="projectData"
              :configs="configs"
            ></table-x>
          </div>
          <div
            v-show="!showindex"
            class="data-form"
            v-loading="loading"
            element-loading-text="正在提交......"
            element-loading-spinner="el-icon-loading"
          >
            <div>
              <h5>{{operationType}}</h5>
            </div>
            <el-form
              :rules="rules"
              style
              ref="projectInfo"
              :model="projectInfo"
              label-width="100px"
            >
              <el-form-item label="项目名称" prop="subjectName">
                <el-input disabled v-model="projectInfo.subjectName"></el-input>
              </el-form-item>
              <el-form-item label="标段" prop="tenders">
                <el-select v-model="projectInfo.tenders" placeholder="请选择标段">
                  <el-option
                    v-for="tender in tenderss"
                    :key="tender"
                    :label="tender"
                    :value="tender"
                  ></el-option>
                  <!-- <el-option label="1标段" value="1标段"></el-option>
                  <el-option label="2标段" value="2标段"></el-option>
                  <el-option label="3标段" value="3标段"></el-option>
                  <el-option label="4标段" value="4标段"></el-option>-->
                </el-select>
              </el-form-item>
              <el-form-item label="专业" prop="major">
                <el-select v-model="projectInfo.major" placeholder="请选择专业">
                  <el-option v-for="major in majorss" :key="major" :label="major" :value="major"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="工程编号" prop="projectId">
                <el-input v-model="projectInfo.projectId"></el-input>
              </el-form-item>
              <el-form-item label="工程名称" prop="projectName">
                <el-input v-model="projectInfo.projectName"></el-input>
              </el-form-item>
              <el-form-item label="项目工程师">
                <el-input v-model="projectInfo.projectEngineer"></el-input>
              </el-form-item>

              <el-form-item style="text-align:right">
                <el-button type="primary" @click="onSubmit">提交</el-button>
                <el-button @click="onCancel">取消</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-col>
    </el-row>
  </el-container>
</template>

<script>
import treeX from "../../components/base/treeX";
import tableX from "../../components/base/tableX";
import { formatDate } from "../../utils/date";

var projectName;

export default {
  data() {
    return {
      operationType: "",
      //表单验证
      rules: {
        tenders: [{ required: true, message: "请选择标段", trigger: "blur" }],
        major: [{ required: true, message: "请选择专业", trigger: "blur" }],
        projectId: [
          { required: true, trigger: "blur", message: "请输入工程编号" }
        ],
        projectName: [
          { required: true, trigger: "blur", message: "请输入工程名称" }
        ]
      },
      loading: false,
      projectInfo: {
        subjectId: "",
        subjectName: "",
        tenders: "",
        major: "",
        projectId: "",
        projectName: "",
        projectEngineer: ""
      },
      showindex: true,
      projectData: [],
      configs: {
        columns: [
          { field: "subjectName", name: "项目名称" },
          { field: "tenders", name: "标段" },
          { field: "major", name: "专业", canSort: true },
          { field: "projectId", name: "工程编号" },
          { field: "projectName", name: "工程名称" },
          { field: "projectEngineer", name: "项目工程师" }
        ],
        operationCol: {
          show: true,
          view: false,
          edit: true,
          delete: false,
          download: false
        },
        showFilterRow: {
          show: true
        },
        operationBtn: {
          show: true,
          add: true,
          output: false
        }
      }
    };
  },
  components: { treeX, tableX },
  created() {
    projectName = this.$store.state.projectInfo.projectName;

    this.initlist();
  },

  computed: {
    tenderss() {
      return this.$store.state.dict.tenders.map(item => {
        return item.tenders;
      });
      // let tenderslist = this.projectData.map(item => {
      //   return item.tenders;
      // });
      // console.log(tenderslist);
      // return Array.from(new Set(tenderslist));
    },
    majorss() {
      return this.$store.state.dict.majors.map(item => {
        return item.dictLabel;
      });
    },
    projectTreeData() {
      console.log(this.projectData);
      let tenderslist = this.projectData.map(item => {
        return item.tenders;
      });
      tenderslist = Array.from(new Set(tenderslist));
      let nodes = [];
      tenderslist.forEach(tenderitem => {
        let node = { label: tenderitem, children: [], level: 0 };

        //该标段下所有的专业，唯一值
        let majorlist = [];
        this.projectData.forEach(proitem => {
          if (proitem.tenders == tenderitem) {
            majorlist.push(proitem.major);
          }
        });
        majorlist = Array.from(new Set(majorlist));

        //返回每个专业的工程树
        majorlist.forEach(major => {
          let nodemajor = { label: major, children: [], level: 1 };
          this.projectData.forEach(proitem => {
            if (proitem.tenders == tenderitem && proitem.major == major) {
              nodemajor.children.push({
                label: proitem.projectId + "-" + proitem.projectName,
                id: proitem.projectId,
                level: 2
              });
            }
          });
          node.children.push(nodemajor);
        });
        nodes.push(node);
      });
      return nodes;
    }
  },

  methods: {
    initlist() {
      let utype = this.$store.state.m_user.userInfo.user_type;
      let company = this.$store.state.m_user.userInfo.company;
      if (utype === "0") {
        this.$api.project.list(projectName).then(res => {
          let abc = [];
          console.log(res);
          if (res.code == 200) {
            if (Array.isArray(res.data)) {
              this.projectData = res.data;
            } else {
              for (let key in res.data) {
                abc = abc.concat(res.data[key]);
              }
              this.projectData = abc;
            }
          }
        });
      } else {
        this.$api.project.listByCompany(projectName, company).then(res => {
          let abc = [];
          console.log(res);
          if (res.code == 200) {
            if (Array.isArray(res.data)) {
              this.projectData = res.data;
            } else {
              for (let key in res.data) {
                abc = abc.concat(res.data[key]);
              }
              this.projectData = abc;
            }
          }
        });
      }
    },

    nodeClick(node) {
      if (node.level && node.level === 2) {
        let row = this.projectData.filter(item => {
          return item.projectId === node.id;
        });
        if (row.length > 0) {
          this.editData(row[0]);
        }
      }
    },

    addNewProject() {
      this.showindex = false;
      this.operationType = "新增工程";
      this.projectInfo = {
        subjectName: this.$store.state.projectInfo.projectName,
        subjectId: this.$store.state.projectInfo.projectName
      };
    },

    editData(row) {
      console.log(row);
      this.operationType = "编辑工程";
      this.projectInfo = {
        id: row.id,
        subjectId: row.subjectId,
        subjectName: row.subjectName,
        tenders: row.tenders,
        major: row.major,
        projectId: row.projectId,
        projectName: row.projectName,
        projectEngineer: row.projectEngineer
      };
      this.showindex = false;
    },

    deleteData(row) {
      console.log(row);
    },

    outputData() {},

    downloadFile(data) {
      console.log(data);
    },

    onSubmit() {
      if (this.operationType == "编辑工程") {
        this.$refs.projectInfo.validate(res => {
          if (res) {
            this.loading = true;
            this.$api.project
              .update(this.projectInfo)
              .then(res => {
                this.loading = false;
                if (res.code == 200) {
                  this.$message.success("更新成功!");
                  this.initlist();
                  this.showindex = true;
                } else {
                  this.$message.error("更新失败!" + res.msg);
                }
              })
              .catch(err => {
                this.loading = false;
                this.$message.error("更新失败!" + err);
              });
          }
        });
      } else {
        // 新增工程
        this.$refs.projectInfo.validate(res => {
          if (res) {
            this.loading = true;
            console.log(this.projectInfo.projectId);
            this.$api.project
              .isProjectIdExist(this.projectInfo.projectId)
              .then(res => {
                if (res.code == 200) {
                  console.log(res);
                  if (res.data) {
                    this.loading = false;
                    this.$message.error(
                      "工程编号:'" + this.projectInfo.projectId + "'已存在"
                    );
                    return;
                  } else {
                    this.$api.project
                      .add(this.projectInfo)
                      .then(res => {
                        this.loading = false;
                        if (res.code == 200) {
                          // 执行插入一条工程到实施表
                          let dd = formatDate(
                            new Date(),
                            "yyyy-MM-dd hh:mm:ss"
                          );
                          this.$api.nodeprogress
                            .add({
                              subject_id: this.projectInfo.subjectName,
                              tenders: this.projectInfo.tenders,
                              major: this.projectInfo.major,
                              project_id: this.projectInfo.projectId,
                              project_name: this.projectInfo.projectName,
                              create_time: dd
                            })
                            .then(res => {
                              if (res.code === 200) {
                                this.initlist();
                                this.$message.success(
                                  "新增成功!插入一条实施记录"
                                );
                              }
                            })
                            .catch(err => {
                              this.$message.error("新增失败11->" + err);
                              console.log(err);
                            });
                          this.showindex = true;
                        } else {
                          this.$message.success("新增失败22!" + res.msg);
                        }
                      })
                      .catch(err => {
                        this.loading = false;
                        this.$message.error("新增失败33!" + err);
                        console.log(err);
                      });
                  }
                }
              })
              .catch(err => {
                this.loading = false;
                this.$message.error("操作失败：" + err);
              });
          }
        });
      }
    },
    onCancel() {
      this.$refs.projectInfo.resetFields();
      this.showindex = true;
    }
  }
};
</script>

<style lang="less" scoped>
.el-container {
  flex-direction: column !important;
}

.project-container {
  height: 100%;

  .el-col {
    height: 100%;
    [class*="-container"] {
      border-radius: 4px;
    }
  }

  .tree-container {
    height: 100%;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15) !important;
  }

  .data-container {
    height: 100%;
    text-align: center;
    .data-list {
      height: 100%;
    }
    .operation {
      margin-bottom: 10px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .el-input {
        width: 200px;
      }
    }

    .data-form {
      text-align: center;
      display: flex;
      justify-items: center;
      flex-direction: column;

      .el-form {
        box-sizing: border-box;
        margin: 0px 100px;
      }

      .el-select {
        display: block;
      }
    }

    .data-table th {
      padding: 10px 0px !important;
    }
    .data-table td {
      padding: 5px 0px !important;
    }
  }
}
</style>